package com.qingge.springboot.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.controller.dto.HandPaperDTO;
import com.qingge.springboot.controller.dto.PagerDTO;
import com.qingge.springboot.entity.PaperQuestion;
import com.qingge.springboot.entity.Question;
import com.qingge.springboot.exception.ServiceException;
import com.qingge.springboot.service.IPagerQuestionService;
import com.qingge.springboot.service.IQuestionService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.common.Result;

import com.qingge.springboot.service.IPaperService;
import com.qingge.springboot.entity.Paper;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黎俊
 * @since 2022-06-14
 */
@RestController
@RequestMapping("/paper")
public class PaperController {

    @Resource
    private IPaperService paperService;
    @Resource
    private IQuestionService questionService;
    @Resource
    private IPagerQuestionService pagerQuestionService;
    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Paper paper) {
        if(paper.getId() ==null){
   // paper.setTiem(DateUtil.now());
   // paper.setUserId(TokenUtils.getCurrentUser().getId());
        }

        paperService.saveOrUpdate(paper);
        return Result.success();
    }
    @PostMapping("/handPaper")
    public Result handPaper(@RequestBody HandPaperDTO handPaperDTO) {
        //删除老的试卷
        UpdateWrapper<PaperQuestion> update = new UpdateWrapper<>();
        update.eq("paper_id",handPaperDTO.getPaperId());
        pagerQuestionService.remove(update);
        if (CollUtil.isEmpty(handPaperDTO.getHandleQuestionIds())){
            throw  new ServiceException("-1","选择题数量不足");
        }
       List<Integer> handleQuestionIds = handPaperDTO.getHandleQuestionIds();
        ArrayList<PaperQuestion> list = new ArrayList<>();
        for (Integer handleQuestionId : handleQuestionIds) {
            PaperQuestion pagerQuestion = new PaperQuestion();
            pagerQuestion.setPaperId(handPaperDTO.getPaperId());
            pagerQuestion.setQuestionId(handleQuestionId);
            list.add(pagerQuestion);
        }

        return Result.success(pagerQuestionService.saveBatch(list));
    }

    // 新增或者更新
    @PostMapping("/takePaper")
    public Result takePaper(@RequestBody PagerDTO pagerDTO) {
        //删除老的试卷
        UpdateWrapper<PaperQuestion> update = new UpdateWrapper<>();
        update.eq("paper_id",pagerDTO.getPaperId());
        pagerQuestionService.remove(update);
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
          queryWrapper.eq("course_id",pagerDTO.getCourseId());
        List<Question> questionList = questionService.list(queryWrapper);
        List<Question> type1List = questionList.stream().filter(question -> question.getType() ==1).collect(Collectors.toList());//选择
        List<Question> type2List = questionList.stream().filter(question -> question.getType()==2).collect(Collectors.toList());//填空
        List<Question> type3List = questionList.stream().filter(question -> question.getType()==3).collect(Collectors.toList());//问答
        if (type1List.size() <pagerDTO.getType1()){
            throw  new ServiceException("-1","选择题数量不足");
        }
        if (type2List.size() <pagerDTO.getType2()){
            throw  new ServiceException("-1","判断题数量不足");
        }
        if (type3List.size() <pagerDTO.getType3()){
            throw  new ServiceException("-1","问答题数量不足");
        }
        //开始随机组卷
        List<PaperQuestion> paperQuestion = getPaperQuestion(type1List.size(), pagerDTO.getType1(), type1List, pagerDTO.getPaperId());
        paperQuestion.addAll(getPaperQuestion(type2List.size(), pagerDTO.getType2(), type2List, pagerDTO.getPaperId()));
        paperQuestion.addAll(getPaperQuestion(type3List.size(), pagerDTO.getType3(), type3List, pagerDTO.getPaperId()));
       pagerQuestionService.saveBatch(paperQuestion);

        return Result.success();
    }

    //封装一个获取试卷合合题目相关联list方法
    private List<PaperQuestion> getPaperQuestion(int questionSize, int pagerQuestionSize,List<Question> source,Integer paperId) {
        List<Integer> typeRandomList = getElelist(questionSize, pagerQuestionSize);
        List<PaperQuestion> list = new ArrayList<>();
        for (Integer index : typeRandomList) {
            Question question = source.get(index);
            PaperQuestion pagerQuestion = new PaperQuestion();
            pagerQuestion.setPaperId(paperId);
            pagerQuestion.setQuestionId(question.getId());
            list.add(pagerQuestion);
        }
        return  list;
    }


    //封装一个获取随机数的方法
    private List<Integer> getElelist(int sourceSize, int resultSize){
        ArrayList<Integer> list = CollUtil.newArrayList();
        for (int i = 0; i<sourceSize;i++){
            list.add(i);
        }
        return RandomUtil.randomEleList(list,resultSize);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        paperService.removeById(id);
        return Result.success();
    }



    @GetMapping("/view/{paperId}")
    public Result view(@PathVariable Integer paperId) {
        List<Question> list = pagerQuestionService.selectQuestions(paperId);
        return Result.success(list);
    }

    @GetMapping
    public Result findAll() {
        return Result.success(paperService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(paperService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        //        if (!"".equals(name)) {
//            queryWrapper.like("username", name);
//        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email", email);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
        return Result.success(paperService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

